package ua.com.softway.db.batch;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import ua.com.softway.db.Persistence;

public class BatchControl {
    private final int batchSize;

    public BatchControl(int batchSize) {
        this.batchSize = batchSize;
    }
    
    private int current;
    
    EntityTransaction transaction;
    EntityManager entityManager;
    
    public void begin() {
        if (transaction == null) {
            EntityManagerFactory entityManagerFactory = Persistence.getEntityManagerFactory();
            
            entityManager = entityManagerFactory.createEntityManager();
            Persistence.setCurrentEntityManager(entityManager);
            
            transaction = entityManager.getTransaction();
            transaction.begin();
        }
    }
    
    public void commit() {
        if (current ++ % batchSize == 0) {
            entityManager.flush();
            transaction.commit();
            
            entityManager.close();
            Persistence.setCurrentEntityManager(null);
            
            transaction = null;
            entityManager = null;
        }
    }
    
    public void forceRollback() {
        current = 0;
        entityManager.clear();
        transaction.rollback();
        
        entityManager.close();
        Persistence.setCurrentEntityManager(null);
        
        transaction = null;
        entityManager = null;
    }
    
    public void forceCommit() {
        current = 0;
        commit();
    }
}
